<template>
  <div class="cesium-map">
    <div id="cesiumContainer"></div>

    <div class="bottom-control" v-if="bottomData">
      <span>帧率: {{ bottomData.fps }}</span>
      <span>网络延迟: {{ bottomData.netDelay }}</span>
      <span>经度: {{ bottomData.lng }}°</span>
      <span>纬度: {{ bottomData.lat }}°</span>
      <span>高度: {{ bottomData.height }}米</span>
      <span>偏航角: {{ bottomData.heading }}°</span>
      <span>俯仰角: {{ bottomData.pitch }}°</span>
      <span>翻滚角: {{ bottomData.roll }}°</span>
    </div>
  </div>
</template>

<script>
import { addskyLayer } from "@/utils/map.js";
export default {
  data() {
    return {
      bottomData: null,
    };
  },

  methods: {
    // 初始化地图
    createdMap() {
      // var cesiumTerrainProvider = new Cesium.CesiumTerrainProvider({
      //   url: window.serviceUrl.terrainUrl,
      // });
      this.viewer = new Cesium.Viewer("cesiumContainer", {
        // terrainProvider: cesiumTerrainProvider,
        contextOptions: {
          webgl: {
            alpha: true,
            depth: true,
            stencil: true,
            antialias: true,
          },
        },
        useBrowserRecommendedResolution: true,
        selectionIndicator: false,
        homeButton: false,
        animation: false, //是否显示动画控件
        baseLayerPicker: false, //是否显示图层选择控件
        geocoder: false, //是否显示地名查找控件
        timeline: false, //是否显示时间线控件
        sceneModePicker: false, //是否显示投影方式控件
        navigationHelpButton: false, //是否显示帮助信息控件
        infoBox: false, //是否显示点击要素之后显示的信息
        imageryProvider: false,
        fullscreenButton: false,
        shouldAnimate: true,
        requestRenderMode: true,
      });
      this.viewer.scene.globe.depthTestAgainstTerrain = false;
      this.viewer.scene.primitives.destroyPrimitives = false;
      this.viewer.scene.postProcessStages._fxaa.enabled = true;
      this.viewer.scene.screenSpaceCameraController.enableCollisionDetection = true;
      this.viewer._cesiumWidget._creditContainer.style.display = "none";
      this.viewer.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
      );

      //指北针
      let options = {};
      // 用于在使用重置导航重置地图视图时设置默认视图控制。接受的值是Cesium.Cartographic 和 Cesium.Rectangle.
      options.defaultResetView = Cesium.Rectangle.fromDegrees(80, 22, 130, 50);
      // 用于启用或禁用罗盘。true是启用罗盘，false是禁用罗盘。默认值为true。如果将选项设置为false，则罗盘将不会添加到地图中。
      options.enableCompass = true;
      // 用于启用或禁用缩放控件。true是启用，false是禁用。默认值为true。如果将选项设置为false，则缩放控件将不会添加到地图中。
      options.enableZoomControls = false;
      // 用于启用或禁用距离图例。true是启用，false是禁用。默认值为true。如果将选项设置为false，距离图例将不会添加到地图中。
      options.enableDistanceLegend = false;
      // 用于启用或禁用指南针外环。true是启用，false是禁用。默认值为true。如果将选项设置为false，则该环将可见但无效。
      options.enableCompassOuterRing = true;
      CesiumNavigation.umd(this.viewer, options);

      this.Global.viewer = this.viewer;
      this.$emit("mapIsLoad", true);
    },

    // 获取底部控件参数
    getControlParams() {
      try {
        setTimeout(() => {
          this.clickMap();

          this.cameraChange = () => {
            let fps, netDelay, lng, lat, height, heading, pitch, roll;
            this.viewer.scene.debugShowFramesPerSecond = true;
            if (this.viewer.scene._performanceDisplay) {
              fps = this.viewer.scene._performanceDisplay._fpsText.data;
              netDelay = this.viewer.scene._performanceDisplay._msText.data;
            }
            lng = Cesium.Math.toDegrees(
              this.viewer.camera.positionCartographic.longitude
            ).toFixed(6);
            lat = Cesium.Math.toDegrees(
              this.viewer.camera.positionCartographic.latitude
            ).toFixed(6);
            height = this.viewer.camera.positionCartographic.height.toFixed(2);
            heading = Cesium.Math.toDegrees(
              Number(this.viewer.camera.heading)
            ).toFixed(6);
            pitch = Cesium.Math.toDegrees(
              Number(this.viewer.camera.pitch)
            ).toFixed(6);
            roll = Cesium.Math.toDegrees(
              Number(this.viewer.camera.roll)
            ).toFixed(6);
            this.bottomData = Object.assign(
              this.bottomData ? this.bottomData : {},
              { fps, netDelay, lng, lat, height, heading, pitch, roll }
            );
          };
          this.viewer.scene.camera.percentageChanged = 0.05;
          this.viewer.camera.changed.addEventListener(this.cameraChange);
        }, 2000);
      } catch (error) {
        console.log("获取底部控件参数方法报错：", error);
      }
    },

    // 左键移动事件
    clickMap() {
      !this.handler &&
        (this.handler = new Cesium.ScreenSpaceEventHandler(this.viewer.canvas));
      this.handler.setInputAction((e) => {
        let cartesian = null;
        let primitive = this.viewer.scene.pick(e.startPosition);
        if (primitive) {
          cartesian = this.viewer.scene.pickPosition(e.startPosition);
        } else {
          let ray = this.viewer.camera.getPickRay(e.startPosition);
          cartesian = this.viewer.scene.globe.pick(ray, this.viewer.scene);
        }
        if (!cartesian) return;
        const cartographic = Cesium.Cartographic.fromCartesian(cartesian);
        const lng = Cesium.Math.toDegrees(cartographic.longitude).toFixed(6);
        const lat = Cesium.Math.toDegrees(cartographic.latitude).toFixed(6);
        this.bottomData = Object.assign(
          this.bottomData ? this.bottomData : {},
          { lng, lat }
        );
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    },
  },

  created() {
    this.viewer = null;
    this.handler = null;
    this.cameraChange = null;
  },

  mounted() {
    this.createdMap();
    this.Global.defaultImageLayer = addskyLayer(
      this.viewer,
      window.serviceUrl.skyImageUrl
    );
    this.getControlParams();
  },

  beforeDestroy() {
    this.handler && this.handler.destroy();
    this.handler = null;
    this.viewer.camera.changed.removeEventListener(this.cameraChange);
    this.cameraChange = null;
  },
};
</script>

<style lang="less" scoped>
.cesium-map,
#cesiumContainer {
  position: relative;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 10;
}

.cesium-map {
  .bottom-control {
    position: fixed;
    bottom: 0;
    display: flex;
    align-items: center;
    width: 100%;
    height: 30px;
    padding: 0 30px;
    box-sizing: border-box;
    background-color: #333333;
    z-index: 11;

    span {
      margin-right: 30px;
      font-size: 10px;
      color: #e6e6e6;
    }
  }
}
</style>

<style lang="less">
.compass {
  top: 30px;
  right: 20px;

  .compass-rotation-marker,
  .compass-outer-ring {
    width: 90%;
    height: 90%;
  }

  .compass-outer-ring {
    background: url(~@/assets/image/toolBar/zhibeizhen.png) no-repeat;
    background-size: 100% 100%;
    background-size: 100%;
  }

  .compass-outer-ring-background,
  .compass-gyro-background,
  .compass-gyro {
    display: none;
  }
}

.cesium-performanceDisplay-defaultContainer {
  display: none !important;
}
</style>